library(survey)
library(dplyr)
library(ggplot2)

# Creating Figure 5.3  
# Wave 1
summary(factor(mil_conf.df$Q8))
mil_conf.df$Q8a <- 0
mil_conf.df$Q8a[mil_conf.df$Q8 < 3] <- 1
summary(factor(mil_conf.df$Q8a))

mil_conf.df$DOV_ETHICAL <- NA
mil_conf.df$DOV_ETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 1] <- 0
mil_conf.df$DOV_ETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 7] <- 1
summary(factor(mil_conf.df$DOV_ETHICAL))

mil_conf.df$DOV_UNETHICAL <- NA
mil_conf.df$DOV_UNETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 1] <- 0
mil_conf.df$DOV_UNETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 8] <- 1
summary(factor(mil_conf.df$DOV_UNETHICAL))


# Creating weighted survey design objects
w1_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight,
    data = mil_conf.df
  )


# Wave 1
# dov_assignment_a == 7 - Ethical generals
ETH <- svyttest(Q8a~DOV_ETHICAL, w1_design)

# dov 8 - Unethical generals
UNETH <- svyttest(Q8a~DOV_UNETHICAL, w1_design)


pt.est <- c(ETH$estimate, UNETH$estimate)
ci.low <- c(ETH$conf.int[1], UNETH$conf.int[1])
ci.high <- c(ETH$conf.int[2], UNETH$conf.int[2])
plot.labs <- c("Ethical\nGenerals","Unethical\nGenerals")
df.plot <- data.frame(Treatment=plot.labs, estimate=pt.est, 
                      lower=ci.low, upper=ci.high)
df.plot$Treatment <- factor(df.plot$Treatment, levels = plot.labs)

ggplot()+
  geom_pointrange(data=df.plot, 
                  mapping = aes(x=Treatment,
                                y=estimate,
                                ymin=lower,
                                ymax=upper),
                  size = 0.5, color = "black")+
  geom_hline(yintercept = 0, color = "red")+
  ylim(-.3,.1)+
  ylab("Difference in Means from Control Condition")+
  xlab("Treatment Condition")+
  theme_bw()
